<?php
/**
 * 产品管理控制器
*
* PHP version 5
*
* @package   Ecga
* @author    Farmer.Li <lixu_01@126.com>
* @copyright 2010 Xingchangxinda Inc.
* @version   SVN: $Id$
*/
namespace Project\Apps\Ecga\Controllers;

use Framework\System\Abstractions\Passport;

use \Project\Apps\Ecga\Controllers\Abstraction\EcgaController;
use \Framework\System\Helper\HttpResponse;
use \Project\Apps\Ecga\Models\Skus as SkusBiz;
use \Framework\Controller\ControllerException;
use \Framework\Mapper\FieldException;
use \Project\Apps\Ecga\Library\Visitor;
use Framework\System\Helper\MongoClient;
use \Framework\System\FileAccessor;
use \Framework\System\FileException;

/**
 * 产品管理控制器
 *
 * PHP version 5
 *
 * @package   Ecga
 * @author    Farmer.Li <lixu_01@126.com>
 * @copyright 2010 Xingchangxinda Inc.
 * @version   Release: <0.1>
 **/
class Skus extends EcgaController
{
    /**
     * 获取有权限的项目 option数组格式
     * 
     * @return array
     */
    private static function _getProjectToOption()
    {
        static $projects = null;
        if (null != $projects) {
            return $projects;
        }
        $ns = get_called_class();
        $tableName = substr($ns, strrpos($ns, '\\') + 1);
        $projects = model('Projects')->getOptions();
        if ($projects) {
            $passport = Visitor::getInstance()->getPassport();
            foreach ($projects as $key => $value) {
                //去除没有查看权限的项目
                if (!$passport->hasProjectPriviage($key, $tableName)) {
                    unset($projects[$key]);
                }
            }
        }
        return $projects;
    }
    
    /**
     * 显示数据表
     *
     * @param HttpRequest $request Http请求
     *
     * @return void
     */
    public static function show($request)
    {
        $page = self::createPage();
        $page->setTitle('产品列表');
        $pageNo = $request->get('page', 'int', 1);
        $filter = array(
            'projectId' => $request->get('projectId', 'int', 0),
            'title' => $request->get('title', 'string'),
            'model' => $request->get('model', 'string'),
            'level' => $request->get('level', 'int'),
            'sku' => $request->get('sku', 'string')
        );
        $projects = self::_getProjectToOption();
        $list = self::createDataList(SkusBiz::getPageQuery($filter))
            ->setCurrentPage($pageNo)
            ->orderBy('id', 'desc');
        $page->assign('list', $list)
            ->assign('projects', $projects)
            ->assign('uri', $request->uri)
			->assign('levelArray', self::levelArray())
            ->assign('filter', $filter);
        HttpResponse::output($page->render('skulist'));
    }
    
    /**
     * 添加产品
     * 
     * @param HttpRequest $request Http请求
     * 
     * @return void
     */
    public static function add($request)
    {
        $page = self::createPage();
        $page->setTitle('添加产品');
        $projectId = $request->get('projectId', 'int');
        $projects = self::_getProjectToOption();
        $page->assign('projectId', $projectId)
            ->assign('levelArray', self::levelArray())
            ->assign('projects', $projects);
        HttpResponse::output($page->render('skudetail'));
    }
    
    /**
     * 执行添加产品
     *
     * @param HttpRequest $request Http请求
     *
     * @return void
     */
    public static function doAdd($request) 
    {
        try {
            $data = self::_getFormData($request);
            $sku = model('Skus')->create();
            self::_save($sku, $data);
        } catch (ControllerException $e) {
            HttpResponse::jsonResult(false, $e->getMessage());
            return false;
        }
        
        $msg = '已成功添加产品 ' . $data['title'];
        self::message($msg);
        HttpResponse::jsonResult(true, $msg);
    }
    
    /**
     * 编辑产品
     *
     * @param HttpRequest $request Http请求
     *
     * @return void
     */
    public static function edit($request)
    {
        $page = self::createPage();
        $page->setTitle('编辑产品');
        $id = $request->get('id', 'int');
        $sku = model('Skus')->get($id);
        if (!$sku) {
            HttpResponse::jsonResult(false, '未找到指定产品');
            return false;
        }
        $projectId = $sku->projectId;
        $projects = self::_getProjectToOption();
        $page->assign('projectId', $projectId)
            ->assign('projects', $projects)
			->assign('levelArray', self::levelArray())
            ->assign('sku', $sku);
        HttpResponse::output($page->render('skudetail'));
    }
    
    /**
     * 执行编辑产品
     *
     * @param HttpRequest $request Http请求
     *
     * @return void
     */
    public static function doEdit($request)
    {
        $id = $request->get('id', 'int');
        $sku = model('Skus')->get($id);
        if (!$sku) {
            HttpResponse::jsonResult(false, '未找到指定产品');
            return false;
        }
        $data = self::_getFormData($request);
        $data['sku'] = $sku->sku;
        try {
            self::_save($sku, $data); 
        } catch (ControllerException $e) {
            HttpResponse::jsonResult(false, $e->getMessage());
            return false;
        }
        $msg = '已成功修改产品 ' . $data['skuName'];
        self::message($msg);
        HttpResponse::jsonResult(true, $msg);
    }
    
    /**
     * 获取表单数据
     * 
     * @param HttpRequest $request Http请求
     * 
     * @return array
     */
    private static function _getFormData($request)
    {
        $data = array(
            'sku' => $request->post('sku', 'string'),
            //'pn' => $request->post('pn', 'string'),
            'model' => $request->post('model', 'string'),
            'title' => $request->post('title', 'string'),
            'level' => $request->post('level', 'int'),
            'srp' => $request->post('srp', 'float'),
            'mop' => $request->post('mop', 'float'),
            'dsp' => $request->post('dsp', 'float'),
            'remark' => $request->post('remark', 'string'),
            'projectId' => $request->post('projectId', 'int')
        );
        return $data;
    }
    /**
     * 执行保存动作
     *
     * @param entity $entity 模型实体
     * @param array  $data   产品数据
     * 
     * @return void
     */
    private static function _save($entity, $data)
    {
        try {
            $entity->setAttributes($data)->save();
        } catch (FieldException $e) {
            switch ($e->getCode()) {
            case FieldException::BLANK_VALUE :
                if ($e->field == 'title') {
                    $message = '产品名称不能为空。';
                } elseif ($e->field == 'sku') {
                    $message = 'sku不能为空。';
                } elseif ($e->field == 'srp') {
                    $message = '厂商建议零售价(SRP)不能为空。';
                } elseif ($e->field == 'mop') {
                    $message = '协定价(MOP)不能为空。';
                } elseif ($e->field == 'projectId') {
                    $message = '所属项目不能为空。';
                } else {
                    throw $e;
                }
                break;
            case FieldException::UNIQUE_VALUE :
                $message = '相同名称/SKU的产品已存在。';
                break;
            case FieldException::INVALUD_VALUE :
                if ($e->field == 'srp') {
                    $message = '厂商建议零售价(SRP)只接受数字类型的值。';
                } elseif ($e->field == 'mop') {
                    $message = '协定价(MOP)只接受数字类型的值。';
                } else {
                    throw $e;
                }
                break;
            default :
                throw $e;
            }
            throw new ControllerException($message);
        }
    }
    
    /**
     * 编辑/查看渠道采集地址
     * 
     * @param HttpRequest $request Http请求
     * 
     * @return void
     */
    public function editSiteUrl($request)
    {
        $page = self::createPage();
        $id = $request->get('id', 'int', '0');
        $sku = model('Skus')->get($id);
        if (!$sku) {
            HttpResponse::jsonResult(false, '未找到指定产品');
            return false;
        }
        $page->setTitle('编辑/查看渠道采集地址');
        $sites = model('Sites')->getSitesByProject($sku->projectId);
        $siteUrls = model('SkuSiteUrls')->getBySKU($sku->sku);
        $page->assign('sites', $sites)
            ->assign('siteUrls', $siteUrls)
            ->assign('id', $id);
        HttpResponse::output($page->render('skusiteurlsdetail'));
    }
    /**
     * 保存sku渠道地址
     * 
     * @param HttpRequest $request Http请求
     * 
     * @return void
     */
    public function doEditSiteUrl($request)
    {
        $id = $request->get('id', 'int', '0');
        $sku = model('Skus')->get($id);
        if (!$sku) {
            HttpResponse::jsonResult(false, '未找到指定产品');
            return false;
        }
        $oldSiteUrls = model('SkuSiteUrls')->getBySKU($sku->sku);
        foreach ($oldSiteUrls as $value) {
            $value->delete();
        }
        $urls = $request->post('suteUrls', 'array');
        $sites = model('Sites')->getSites();
        $skuSiteUrlsModel = model('SkuSiteUrls');
        foreach ($urls as $siteId => $url) {
            if (!$sites[$siteId]) {
                continue;
            }
            $data = array(
                'sku' => $sku->sku,
                'siteId' => $siteId,
                'skuUrl' => $url
            );
            $skuSiteUrlsModel->create()
                ->setAttributes($data)
                ->save();
        }
        $msg = '已成功修改产品: ' . $sku->title . " 的渠道采集地址";
        self::message($msg);
        HttpResponse::jsonResult(true, $msg);
    }
    
    /**
     * 下载导入模版
     * 
     * @param HttpRequest $request Http请求
     * 
     * @return void
     */
    public static function downImportSKUTemplate($request)
    {
        $page = self::createPage();
        $page->setTitle('下载批量导入模版');
        $projects = self::_getProjectToOption();
        $page->assign('projects', $projects);
        HttpResponse::output($page->render('downimportskutemplate'));
    }
    
    /**
     * 创建格式化的CVS 模版
     * 
     * @param HttpRequest $request Http请求
     * 
     * @return void
     */
    public function createFormatCsv($request)
    {
        $projectId = $request->post('projectId', 'int');
        $project = model('Projects')->get($projectId);
        if (!$project) {
            HttpResponse::jsonResult(false, '指定的项目不存在');
            return false;
        }
        $allowProjects = self::_getProjectToOption();
        if (!array_key_exists($projectId, $allowProjects)) {
            self::message('未授权的项目', 'warning', 'skus.php?a=show');
        }
        $result = array();
        $skus = model('Skus')->getByProjectId($projectId);
        $sites = model('Sites')->getSites();
        $filename = mb_convert_encoding(
            $project->projectName . '产品渠道地址导入模板.csv', 
            'gbk', 
            'utf-8'
        );
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename={$filename}");
        header("Pragma: no-cache");
        header("Expires: 0");
        $outstream = fopen("php://output", "w+");
        fwrite($outstream, chr(0xEF).chr(0xBB).chr(0xBF));  
        fputcsv(
            $outstream,
            array(
                '注意事项:', 
                '请按照导出的格式填写您要导入的数据.' . 
                '请不要更改列顺序否则将导致数据混乱出错.' . 
                '一个sku对应渠道地址为一行.' . 
                '请填写在系统中已存在的SKU的渠道地址.在系统中不存在的SKU将被跳过.'
            )
        );
        fputcsv($outstream, array('sku', '中文名称', '渠道ID(见渠道管理)', 'URL'));
        foreach ($skus as $sku) {
            $urls = model('SkuSiteUrls')->getBySKU($sku->sku);
            foreach ($sites as $site) {
                fputcsv(
                    $outstream, 
                    array(
                        $sku->sku, 
                        $sku->title, 
                        $site['id'], 
                        $urls[$site['id']]['skuUrl']
                    )
                );
            }
        }
        fclose($outstream);
    }
    
    /**
     * 批量导入
     * 
     * @param HttpRequest $request Http请求
     * 
     * @return void
     */
    public function batchImportSKU($request)
    {
        $page = self::createPage();
        $page->setTitle('批量导入产品');
        $projects = self::_getProjectToOption();
        $page->assign('projects', $projects);
        HttpResponse::output($page->render('batchimportsku'));
    }
    
    /**
     * 执行批量导入
     *
     * @param HttpRequest $request Http请求
     *
     * @return void
     */
    public function doBatchImportSKU($request)
    {
        $file = $request->files('importFile');
        //由于FileAccessor对文件类型的限制, 这里绕过框架上传文件的验证
        $file['type'] = 'image/jpeg';
        $data = array();
        $user = Visitor::getInstance();
        $data['userId'] = $user->userId;
        try {
            $data['fileId'] = $this->_uploadFile($file);
            model('importFiles')->create()->setAttributes($data)->save();
        } catch (FieldException $ex) {
            self::message(
                '保存导入文件队列时发送错误: ' . $ex->getMessage(), 
                'warning',
                'skus.php?a=show'
            );
        }
        
        self::message('文件上传成功, 请等待后台进行导入!', 'notice', 'skus.php?a=show');
    }
    
    /**
     * 上传文件
     *
     * @param array &$file 上传文件数组
     *
     * @return string
     */
    private static function _uploadFile(&$file)
    {
        if ($file['error'] != UPLOAD_ERR_NO_FILE) {
            try {
                $path = FileAccessor::uploadFile($file, 'image', SITE_ID);
            } catch (FileException $e) {
                $path = '';
                self::message(
                    sprintf('对不起，头像上传失败，原因是：%s', $e->getMessage()),
                    'warning'
                );
            }
        } else {
            $path = '';
        }
        return $path;
    }
	/**
	 * 产品星级
	 *
	 * @return array
	 */
	public static function levelArray()
	{
		$return = array(
			'1' => '一星',
			'2' => '二星',
			'3' => '三星'
		);
		return $return;
	}
}
?>